﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model.ViewModel;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace DeHeng_Mes.Thread
{
    public class MesDataPush
    {
        OrderDao orderDao = new OrderDao();
        ViewDao viewDao = new ViewDao();

        public async Task pushTask()
        {
            Tools.ProduceLogText("Mes数据推送线程启动成功！");

            while (true)
            {
                await Task.Delay(5000);

                try
                {
                    // 查询生产中的工单
                    List<OrderStatus> orderStatuses = orderDao.QueryOrder();

                    // 查询工单绑定的工件码
                    List<KeyValuePair<string, List<OrderTrace>>> keyValuePairList = new List<KeyValuePair<string, List<OrderTrace>>>();

                    foreach (var item in orderStatuses)
                    {
                        List<OrderTrace> order = orderDao.QueryOrderTrace(item.OrderId);

                        KeyValuePair<string, List<OrderTrace>> a = new KeyValuePair<string, List<OrderTrace>>(item.LineName,order);

                        keyValuePairList.Add(a);
                    }

                    if (keyValuePairList.Count <= 0)
                        continue;

                    foreach (var keyValuePair in keyValuePairList)
                    {
                        foreach (var orderTrace in keyValuePair.Value)
                        {
                            if (orderTrace.TraceId.Contains("LAC-84001052-1"))
                                continue;

                            string code = Tools.GetHashCodeFromPushMes(orderTrace.OrderId, orderTrace.TraceId, orderTrace.CreateTime);

                            string dataFrom = keyValuePair.Key;

                            PushPart(orderTrace, code, dataFrom);

                            StationPart(orderTrace, code, dataFrom);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"组装或者推送工厂Mes数据失败，原因是{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 推送单件数据
        /// </summary>
        /// <param name="orderTraces"></param>
        private void PushPart(OrderTrace orderTrace, string code, string dataFrom)
        {
            try
            {
                if (orderTrace.PartPushStatus.Equals("1"))
                    return;

                // 推送单件上件绑定数据
                int count = viewDao.PushPartData(new LineMesData()
                {
                    OrderId = orderTrace.OrderId,
                    TraceId = orderTrace.TraceId,
                    CreateTime = orderTrace.CreateTime,
                    DataFrom = dataFrom,
                    DataId = code,
                });

                if (count > 0)
                {
                    orderDao.UpdatePartPushStatus(orderTrace.OrderId, orderTrace.TraceId);
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"推送单件数据失败，原因是{e.Message}");
            }
        }

        /// <summary>
        /// 推送过站数据
        /// </summary>
        private void StationPart(OrderTrace orderTrace, string code, string dataFrom)
        {
            try
            {
                if (orderTrace.StationPushStatus.Equals("1"))
                    return;

                int traceId = orderDao.GetCodeId(orderTrace.TraceId);

                // 初始化过站信息列表
                Dictionary<int, PartProcess> partProcesses = new Dictionary<int, PartProcess>();

                if (traceId > 0)
                {
                    List<int> processIds = orderDao.GetProcessIds(traceId);

                    if (processIds?.Count > 0)
                    {
                        foreach (var processId in processIds)
                        {
                            PartProcess partProcess = orderDao.GetProcessData(processId);

                            if (partProcess == null)
                                continue;

                            partProcesses.Add(processId, partProcess);
                        }
                    }
                }

                foreach (var partProcess in partProcesses)
                {
                    // 获取工站对应工序
                    string operations = MappingTable.GetOperationId(partProcess.Value.Station);

                    string stationCode = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, partProcess.Value.Station, partProcess.Value.EndTime);

                    // 拼接过站数据进行推送
                    int stationDataRecord = viewDao.PushStationData(new LineMesDataTrace()
                    {
                        DataId = code,
                        DataTraceId = stationCode,
                        Station = partProcess.Value.Station,
                        Process = operations,
                        Result = partProcess.Value.Result,
                        CreateTime = partProcess.Value.EndTime,
                        StartTime = partProcess.Value.StartTime,
                        EndTime = partProcess.Value.EndTime,
                        DataFrom = dataFrom,
                        UserId = "",
                    }, orderTrace.TraceId);

                    if (stationDataRecord > 0)
                    {
                        orderDao.UpDateStationStatus(traceId, partProcess.Value.Station);

                        // 判断是否是最后一序
                        bool isEndStation = MappingTable.GetEndStation(partProcess.Value.Station);

                        /*if (partProcess.Value.Station.Contains("ST20") || partProcess.Value.Station.Contains("ST10"))
                            orderDao.UpDateStationStatus(orderTrace.OrderId, orderTrace.TraceId);
                        else if (isEndStation)
                            orderDao.UpDateStationStatus(orderTrace.OrderId, orderTrace.TraceId);*/
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"推送过站数据失败，原因是{ex.Message}");
            }
        }
        /*
                /// <summary>
                /// 推送投料数据
                /// </summary>
                /// <param name="orderTraces"></param>
                private void MaterialPart(OrderTrace orderTrace, string code, string dataFrom)
                {
                    try
                    {
                        if (orderTrace.MaterialPushStatus.Equals("1"))
                            return;

                        int traceId = orderDao.GetCodeId(orderTrace.TraceId);

                        if (traceId > 0)
                        {
                            List<CodeBatchCode> batchs = orderDao.GetBatchIds(traceId);

                            if (batchs?.Count > 0)
                            {
                                foreach (var batchId in batchs)
                                {
                                    TraceBatchCode batchData = orderDao.GetBatchData(batchId.BatchId);

                                    if (batchData == null)
                                        continue;

                                    string dataDtlId = Tools.GetHashCodeFromPushMes(batchData.BatchId, batchId.BatchCount.ToString(), batchId.CreateTime);

                                    // 获取工站对应工序
                                    string operations = MappingTable.GetOperationId(batchId.Station);

                                    viewDao.PushBatchData(new LineMesDataDtl()
                                    {
                                        DataId = code,
                                        DataDtlId = dataDtlId,
                                        CreateTime = batchId.CreateTime,
                                        BatchId = batchData.BatchId,
                                        Count = batchId.BatchCount,
                                        ProcessId = operations,
                                        DataFrom = dataFrom,
                                    });

                                    // 更新推送状态
                                    orderDao.UpdateBatchStatus(batchId);

                                    // 判断是否是最后一序
                                    bool isEndStation = MappingTable.GetEndStation(batchId.Station);

                                    if (isEndStation)
                                        orderDao.UpDateStationStatus(orderTrace.OrderId, traceId);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.ProduceLogTextError($"推送批次数据失败，原因是{ex.Message}");
                    }
                }*/

        /// <summary>
        /// 推送工艺数据
        /// </summary>
        /// <param name="orderTraces"></param>
        private void OperationPart(OrderTrace orderTrace, string code)
        {
            /*if (!orderTrace.OperationPushStatus.Equals("1"))
                return;*/
            return;
        }
    }
}
